package com.spring.crm.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spring.crm.conf.CommonResult;
import com.spring.crm.conf.CryptHelper;
import com.spring.crm.conf.ResultCode;
import com.spring.crm.conf.TokenUtil;
import com.spring.crm.entity.Sales;
import com.spring.crm.entity.User;
import com.spring.crm.mapper.UserMapper;
import javafx.application.Application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 何卓
 * @since 2022-01-10
 */
@RestController
@RequestMapping("/api/crm/user")
public class UserController {
    private final static Logger LOGGER = LoggerFactory.getLogger(Application.class);
    @Resource
    private UserMapper userMapper;
    @CrossOrigin(origins = "*")
    @PostMapping("login")
    public CommonResult login(@RequestBody User record, HttpServletResponse response) {
        CommonResult rs;
        try {
            if(record.getUsername()==null){
                return CommonResult.failed("用户名（唯一标志）不能为空");
            }
            Map userMap = new HashMap();
            userMap.put("username",record.getUsername());
            userMap.put("password", CryptHelper.encrypt(record.getPassword()));
            List<User> user = userMapper.selectByMap(userMap);
            if(user.size()>0){
//                Cookie cookie = new Cookie("auth", "123456");
//                response.addCookie(cookie);
                String token = TokenUtil.createToken(user.get(0).getUserId());
                return CommonResult.success(user,token);

            }
            return CommonResult.failed("密码错误");
        }catch(Exception ex){
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }

    @CrossOrigin(origins = "*")
    @PostMapping("insert")
    public CommonResult insertOne(@CookieValue(value = "userAuth",defaultValue = "") String userAuth,@RequestBody User record) {
        CommonResult rs;
        try {
            String[] authArr = userAuth.split("");
            if(!Arrays.asList(authArr).contains("b")){
                return CommonResult.failed("没有创建用户权限");
            }
            if(record.getUsername()==null){
                return CommonResult.failed("用户名（唯一标志）不能为空");
            }
            Map userMap = new HashMap();
            userMap.put("username",record.getUsername());
            List<User> user = userMapper.selectByMap(userMap);
            if(user.size()>0){
                return CommonResult.failed("用户名重复");
            }
            LocalDateTime dd = LocalDateTime.now(); // 注意是util包下的Date
            record.setCreateTime(dd.toString());
            record.setPassword(CryptHelper.encrypt(record.getPassword()));
            int ret = userMapper.insert(record);
            if (ret != 1){
                rs = CommonResult.failed();
            }else {
                JSONObject data = new JSONObject();
                data.put("userId",record.getUserId());
                rs = CommonResult.success(data);
            }
        }catch(Exception ex){
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }
    @CrossOrigin(origins = "*")
    @GetMapping("condition")
    public CommonResult selectByCondition(@CookieValue(value = "userAuth",defaultValue = "") String userAuth,@RequestParam Map<String,String> map) {
        CommonResult rs;
        try {

            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            if(map.containsKey("username")){
                queryWrapper.like("username",map.get("username"));
            }
            if(map.containsKey("realname")){
                queryWrapper.like("realname",map.get("realname"));
            }
            if(map.containsKey("userId")){
                queryWrapper.eq("user_id",map.get("userId"));
            }
            if(map.containsKey("userType")){
                if("23".equals(map.get("userType"))){
                    queryWrapper.in("user_type","2","3");
                }else{
                    queryWrapper.eq("user_type",map.get("userType"));
                }
            }
            if(map.containsKey("staffRole")){
                queryWrapper.eq("staff_role",map.get("staffRole"));
            }
            //queryWrapper.orderByAsc("num");
            Page<User> page = new Page<>(Long.valueOf(map.get("current")),Long.valueOf(map.get("size")));
            IPage<User> userIPage = userMapper.selectPage(page,queryWrapper);
            Integer selectCount = Math.toIntExact(userMapper.selectCount(queryWrapper));
            List<User> list = userIPage.getRecords();
            rs = CommonResult.success(list,selectCount);
        }catch(Exception ex){
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }

    @CrossOrigin(origins = "*")
    @DeleteMapping ("delete")
    public CommonResult deleteOne(@RequestBody User record) {
        CommonResult rs;
        try {
            User user = userMapper.selectById(record.getUserId());
            if(user==null){
                return CommonResult.failed(ResultCode.DATA_Not_Exist_ERROR);
            }
            int ret = userMapper.deleteById(record.getUserId());
            if (ret != 1) {
                rs = CommonResult.failed();
            } else {
                rs = CommonResult.success("");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }

    @CrossOrigin(origins = "*")
    @PutMapping("update")
    public CommonResult updateOne(@RequestBody User record) {
        CommonResult rs;
        try {
            User user = userMapper.selectById(record.getUserId());
            if(user==null){
                return CommonResult.failed(ResultCode.DATA_Not_Exist_ERROR);
            }
            if(record.getPassword()!=null){
                record.setPassword(CryptHelper.encrypt(record.getPassword()));
            }
            int ret = userMapper.updateById(record);
            if (ret != 1) {
                rs = CommonResult.failed();
            } else {
                JSONObject data = new JSONObject();
                data.put("userId", record.getUserId());
                rs = CommonResult.success(data);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }

    @CrossOrigin(origins = "*")
    @PostMapping("updatePassword")
    public CommonResult updatePassword(@RequestBody  Map<String,Object> map) {
        CommonResult rs;
        try {
            LOGGER.info(map.get("oldPassword").toString());
            Map userMap = new HashMap();
            userMap.put("user_id",map.get("userId"));
            userMap.put("password", CryptHelper.encrypt(map.get("oldPassword").toString()));
            List<User> user = userMapper.selectByMap(userMap);
            if(user.size()>0){
//                Cookie cookie = new Cookie("auth", "123456");
//                response.addCookie(cookie);
                User record = new User();
                record.setUserId(map.get("userId").toString());
                record.setPassword(CryptHelper.encrypt(map.get("newPassword").toString()));
                int ret = userMapper.updateById(record);
                if (ret != 1) {
                    return CommonResult.failed("修改失败");
                } else {
                    return CommonResult.success("修改成功");
                }

            }
            return CommonResult.failed("密码错误");
        } catch (Exception ex) {
            ex.printStackTrace();
            rs = CommonResult.failed(ex.toString());
        }
        return rs;
    }
}
